<template>
  <el-dialog :title="showTitle" :visible="dialogVisible" width="630px" class="dialog" @close="handleClose">
    <el-form ref="dialogForm" label-position="right" :model="form" label-width="140px" :inline="true" :rules="rules">
      <!-- 商品名称 -->
      <el-form-item prop="skuName" label="商品名称：" class="form-item">
        <el-input v-model="form.skuName" placeholder="请输入" maxlength="15" type="text" show-word-limit />
      </el-form-item>
      <!-- 品牌 -->
      <el-form-item prop="brandName" label="品牌：" class="form-item">
        <el-input v-model="form.brandName" placeholder="请输入" maxlength="10" type="text" show-word-limit />
      </el-form-item>
      <!-- 商品价格 -->
      <el-form-item prop="price" label="商品价格（元）：" class="form-item">
        <el-input v-model="form.price" class="price" placeholder="请输入" type="text">
          <div slot="append" class="upDown">
            <el-button :disabled="form.price>=9999.99?true:false" icon="el-icon-arrow-up" style="border-bottom: 1px solid #dcdfe6;" @click="upPrice" />
            <el-button :disabled="form.price<=0.50?true:false" icon="el-icon-arrow-down" @click="downPrice" />
          </div>
        </el-input>
      </el-form-item>
      <!-- 商品类型 -->
      <el-form-item prop="classId" label="商品类型：" class="form-item">
        <el-select v-model="form.classId" placeholder="请选择">
          <el-option v-for="item in goodsClass" :key="item.classId" :label="item.className" :value="item.classId" />
        </el-select>
      </el-form-item>
      <!-- 规格 -->
      <el-form-item prop="unit" label="规格：" class="form-item">
        <el-input v-model="form.unit" placeholder="请输入" maxlength="10" type="text" show-word-limit />
      </el-form-item>
      <!-- 商品图片 -->
      <el-form-item prop="skuImage" label="商品图片：">
        <el-upload
          v-model="form.skuImage"
          class="avatar-uploader"
          :show-file-list="false"
          action=""
          :http-request="uploadSectionFile"
        >
          <img v-if="form.skuImage" :src="form.skuImage" class="avatar">
          <i v-else class="el-icon-upload avatar-uploader-icon" />
          <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过100kb</div>
        </el-upload>
      </el-form-item>
    </el-form>
    <!-- 底部按钮 -->
    <div slot="footer" class="dialog-footer">
      <el-button class="cancel" @click="handleClose">取 消</el-button>
      <el-button v-loading="loading" type="primary" class="confirm" @click="handleSubmit">确 认</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { postAddSkuAPI, putSkuAlterAPI } from '@/api/goods'
import { postFileUploadAPI } from '@/api/user'
export default {
  name: '',
  components: {},
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    },
    goodsClass: {
      type: Array,
      default: () => ([])
    }
  },
  data() {
    return {
      form: {
        price: '',
        skuImage: ''
      },
      rules: {
        skuName: [
          { required: true, message: '请输入' }
        ],
        brandName: [
          { required: true, message: '请输入' }
        ],
        price: [
          { required: true, message: '请输入' }
        ],
        skuClass: [
          { required: true, message: '请选择' }
        ],
        unit: [
          { required: true, message: '请输入' }
        ],
        skuImage: [
          { required: true, message: '请上传' }
        ]
      },
      loading: false
    }
  },
  computed: {
    showTitle() {
      return `${this.form.createTime ? '修改' : '新增'}商品`
    }
  },
  watch: {
    form: {
      handler() {
        if (this.form.price !== '') {
          if (this.form.price > 9999.99) {
            this.form.price = 9999.99
          }
          if (this.form.price < 0.5) {
            this.form.price = 0.5
          }
        }
      },
      deep: true
    }
  },
  created() {
  },
  methods: {
    // 退出弹框
    handleClose() {
      this.$emit('update:dialogVisible', false)
      this.$refs.dialogForm.resetFields()
      this.form = {}
    },
    // 新增修改商品
    async handleSubmit() {
      try {
        await this.$refs.dialogForm.validate()
        this.loading = true
        this.form.createTime ? await putSkuAlterAPI(this.form) : await postAddSkuAPI(this.form)
        this.$message.success(`${this.form.createTime ? '修改' : '新增'}商品成功`)
        this.handleClose()
        this.$parent.getSkuSearch()
      } catch (error) {
        this.$message.error(error.response.data)
        console.log(error)
      } finally {
        this.loading = false
      }
    },
    // 覆盖默认的上传行为，自定义图片上传请求
    async uploadSectionFile({ file }) {
      //* 1. 图片处理
      const isJPGPNG = (file.type === 'image/jpeg' || file.type === 'image/png')
      const isLt100kb = file.size < (100 * 1024)
      if (!isJPGPNG) {
        this.$message.error('上传图片只能是 jpg 和 png 格式!')
        return isJPGPNG
      }
      if (!isLt100kb) {
        this.$message.error('上传图片大小不能超过 100kb!')
        return isLt100kb
      }
      //* 2. 图片上传
      const fromData = new FormData()
      fromData.append('fileName', file)
      const { data, status } = await postFileUploadAPI(fromData)
      if (status !== 200) {
        return this.$message.error('上传失败')
      }
      this.form.skuImage = data
    },
    // 加钱
    upPrice() {
      this.form.price = +this.form.price + 0.5
    },
    // 减钱
    downPrice() {
      this.form.price = +this.form.price - 0.5
    }
  }
}
</script>
<style lang="scss">
.dialog{
  .el-dialog{
  border-radius: 10px;
  }
  .el-dialog__body{
    padding: 10px 40px;
  }
}
  .avatar-uploader .el-upload {
    position: relative;
    overflow: hidden;
    background: #f3f6fb;
    border: 1px dashed #d8dde3;
    border-radius: 4px;
    cursor: pointer;
  }
  .form-item{
    .el-form-item__content{
      width: 70% !important;
      .el-select{
        width: 100%;
      }
    }
    .price{
      .el-input__inner{
        text-align: center;
      }
    }
    .el-input-group__append{
      padding: unset;
      width: 47px;
      .upDown{
        .el-button{
          padding: unset;
          flex: 1;
          margin-left: unset;
          margin: 0;
        }
      }
    }
  }
</style>
<style scoped lang='scss'>
.dialog-footer{
  text-align: center;
}
.form-item{
  width: 100%;
}
.cancel{
    align-items: center;
    width: 80px!important;
    height: 36px;
    padding: 0;
    background-color: #fbf4f0!important;
    border: none;
    color: #655b56!important;
}
.confirm{
    align-items: center;
    width: 80px!important;
    height: 36px;
    padding: 0;
    background: linear-gradient(135deg,#ff9743,#ff5e20)!important;
    border: none;
    margin-left: 34px;
}
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 84px;
    height: 84px;
    line-height: 84px;
    text-align: center;
  }
  .avatar {
    width: 84px;
    height: 84px;
    display: block;
  }
  .upDown{
    display: flex;
    flex-direction: column;
    flex-wrap: wrap;
    width: 46px;
    height: 40px;
  }
</style>
